package cc.laop.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

/**
 * 获取当前系统信息
 */
public class SystemInfoUtils {

    private static final Logger logger = LoggerFactory.getLogger(SystemInfoUtils.class);

    /**
     * 本地IP
     *
     * @return IP地址
     * @throws UnknownHostException
     */
    public static String getIp() {
        InetAddress localHost;
        try {
            localHost = InetAddress.getLocalHost();
            String ip = localHost.getHostAddress();
            return ip;
        } catch (UnknownHostException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取用户机器名称
     *
     * @return
     * @throws UnknownHostException
     */
    public String getHostName() {
        InetAddress localHost;
        try {
            localHost = InetAddress.getLocalHost();
            return localHost.getHostName();
        } catch (UnknownHostException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取Mac地址
     *
     * @return Mac地址，例如：F0-4D-A2-39-24-A6
     */
    public static String getMac() {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            return getMac(localHost);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    private static String getMac(InetAddress localHost) throws SocketException {
        NetworkInterface byInetAddress = NetworkInterface.getByInetAddress(localHost);
        byte[] hardwareAddress = byInetAddress.getHardwareAddress();
        if (hardwareAddress != null) {
            return getMacFromBytes(hardwareAddress);
        } else {
            return null;
        }
    }

    /**
     * 获取当前系统名称
     *
     * @return 当前系统名，例如： windows xp
     */
    public static String getOsName() {
        Properties sysProperty = System.getProperties();
        // 系统名称
        String systemName = sysProperty.getProperty("os.name");
        return systemName;
    }

    /**
     * 获取系统版本
     *
     * @return
     */
    public static String getOsVersion() {
        Properties sysProperty = System.getProperties();
        // 系统名称
        String systemVersion = sysProperty.getProperty("os.version");
        return systemVersion;
    }

    private static String getMacFromBytes(byte[] bytes) {
        StringBuffer mac = new StringBuffer();
        byte currentByte;
        boolean first = false;
        for (byte b : bytes) {
            if (first) {
                mac.append(":");
            }
            currentByte = (byte) ((b & 240) >> 4);
            mac.append(Integer.toHexString(currentByte));
            currentByte = (byte) (b & 15);
            mac.append(Integer.toHexString(currentByte));
            first = true;
        }
        return mac.toString().toUpperCase();
    }

    /**
     * 获取本地IP列表 （多网卡）
     *
     * @return
     */
    public static List<String[]> getNetInfo() {
        List<String[]> list = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> interfaces = null;
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                Enumeration<InetAddress> addresss = ni.getInetAddresses();
                while (addresss.hasMoreElements()) {
                    InetAddress nextElement = addresss.nextElement();
                    if (nextElement instanceof Inet4Address) {
                        String hostAddress = nextElement.getHostAddress();
                        String mac = getMac(nextElement);
                        if (StringUtils.isNotEmpty(hostAddress) && StringUtils.isNotEmpty(mac)) {
                            String[] netinfo = new String[]{hostAddress, mac};
                            list.add(netinfo);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return list;
    }

    public static void main(String[] args) {
        System.out.println("os: " + getOsName());
        List<String[]> list = getNetInfo();
        for (String[] str : list) {
            System.out.println("ip: " + str[0] + ", mac: " + str[1]);
        }
    }
}